package sporteam.web.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@SuppressWarnings("serial")
public class GetAuthCodeServlet extends HttpServlet {

	final static String appID = "324246104303611";
	final static String appSecret = "b481089a1cd6c688c41ad1c6fcd0a737";
	final String redirectURI = "https://sporteamws.appspot.com/test";

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String code = req.getParameter("code");

		String token_request_url = "https://graph.facebook.com/oauth/access_token?"
				+ "client_id="
				+ appID
				+ "&redirect_uri="
				+ redirectURI
				+ "&client_secret=" + appSecret + "&code=" + code;

		String access_token = retrieveAccessToken(token_request_url); 

		resp.sendRedirect("/fbreg?access_token=" + access_token + "&code=" + code);
	}

	private String retrieveAccessToken(String token_request_url) throws IOException {
		URL url = new URL(token_request_url);
		URLConnection url_con = url.openConnection();
		BufferedReader in = new BufferedReader(new InputStreamReader(
				url_con.getInputStream()));
		String answer = in.readLine();
		if(in.readLine()  != null){
			//did not retrieve access token
		}
		in.close();
		
			//answer = "access_token=ACCESS_TOKEN_GIBRISH&expires=EXPIRES_TIME_MS"
		String access_token = answer.split("&")[0].split("=")[1];	//Finally, I've retrieved the access token !!!
		return access_token;
		
	}
	
}



